package com.xh.controll;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.xh.entiy.Course;
import com.xh.entiy.CourseCatalog;
import com.xh.entiy.CourseVideo;
import com.xh.entiy.TreeModel;
import com.xh.service.CatalogService;
import com.xh.service.CourseService;
import com.xh.service.CourseVideoService;

@Controller
@RequestMapping("/admin")
public class AdminControl {
	
	@Autowired
	private CourseService courseService;
	@Autowired
	private CatalogService catalogService;
	@Autowired
	private CourseVideoService courseVideoService;
	
	@RequestMapping(value="/savecourse",method=RequestMethod.POST)
	@ResponseBody
	public Course saveCourse(Course course,HttpServletRequest request){
		course=courseService.saveOrUpdate(course);
		System.out.println(request.getServletContext().getRealPath("/admin"));
		return course;
	}
	
	@RequestMapping(value="/getcourse",method=RequestMethod.GET)
	@ResponseBody
	public List<Course> getCourse(){
		System.out.println("**");
		List<Course> courses=courseService.getCourses();
		for (Course c : courses) {
			System.out.println(c.getId()+"  "+c.getName()+"  "+c.getDescript()+"  "+c.getCreate_time());
		}
		return courses;
	}
	
	@RequestMapping(value="/getDescript",method=RequestMethod.POST)
	@ResponseBody
	public String getDescript(@RequestParam("catalogid") Integer id){
		CourseCatalog catalog=catalogService.findById(id);
		String descript=catalog.getDescript();
		return descript;
		}

	
	@RequestMapping(value="/saveCatalog")
	@ResponseBody
	public void saveCatalog(@RequestParam("cid") Integer cid,CourseCatalog catalog){
		Course course=courseService.getCourse(cid);
		catalog.setCourse(course);
		System.out.println(course.getId()+"  "+catalog.getName());
		catalogService.saveCatalog(catalog);
	}
	
	@RequestMapping(value="/upload",method=RequestMethod.POST)
	@ResponseBody
	public String upload(@RequestParam("multifile")  MultipartFile file,@RequestParam("id") Integer id,@RequestParam("name") String name,@RequestParam("description") String descript) throws UnsupportedEncodingException{
		System.out.println(id);
		String path=getPath(id);
		if(!file.isEmpty()){
			File f=new File("d:/course/"+path);			
			//文件名乱码设置
			String filename=new String(file.getOriginalFilename().getBytes("iso-8859-1"), "utf-8");
			if(!f.exists()) f.mkdirs();
			try {
				CourseVideo cv=new CourseVideo();
				CourseCatalog cc=catalogService.findById(id);
				cv.setName(name);
				cv.setDescription(descript);
				cv.setCatalog(cc);
				cv.setUpload_time(new Date());
				courseVideoService.saveVideo(cv);
				BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(
						new File(f.getPath()+"/"+filename)));
				out.write(file.getBytes());
				out.flush();
				out.close();
				return "上传成功！";
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "失败！";
	}
	
	private String getPath(Integer id) {
		String path="";
		CourseCatalog catalog=catalogService.findById(id);
		if (catalog.getParentId()!=null){
			path=getPath(catalog.getParentId());
		}
		else{
			Course c=catalog.getCourse();
			path=catalog.getName();
		}
		return path+"/"+catalog.getName();
	}

	@RequestMapping(value="/deleteCatalog",method=RequestMethod.POST)
	@ResponseBody
	public void deleteCatalog(@RequestParam("cid") Integer cid,CourseCatalog catalog){
		System.out.println("accept delete!");
		deleteCatalogs(catalog.getId());
	}
	
	private void deleteCatalogs(Integer id) {
		List<CourseCatalog> children=catalogService.findByParentId(id);
		if(children!=null){
			for (CourseCatalog c : children) {
				deleteCatalogs(c.getId());				
			}
		}
		System.out.println("===>"+id);
		catalogService.deleteCatalogs(id);
	}

	@RequestMapping(value="/getCTree/{id}")
	@ResponseBody
	public List<TreeModel> getCourseTree(@PathVariable("id") Integer id) throws JsonProcessingException{
		List<TreeModel> tm=new ArrayList<>();	
		List<CourseCatalog> catalogs=catalogService.getCatalog(id);
		for(int i=0;i<catalogs.size();i++){
			CourseCatalog cc=catalogs.get(i);
			if(cc.getParentId()==null){
				TreeModel t=new TreeModel();
				t.setId(cc.getId()); t.setText(cc.getName());
				t.setChildren(getchildren(cc.getId(),catalogs));
				tm.add(t);				
			}
		}
//		System.out.println(objectMapper.writeValueAsString(tm));
		return tm;
	}

	private List<TreeModel> getchildren(Integer id, List<CourseCatalog> catalogs) {
		List<TreeModel> tmp=new ArrayList<>();
		for (CourseCatalog c : catalogs) {
			if(c.getParentId()==id){
				TreeModel t=new TreeModel();
				t.setId(c.getId()); t.setText(c.getName());
				t.setChildren(getchildren(c.getId(), catalogs));
				tmp.add(t);
			}
		}
		return tmp;
	}
		
}
